<?php

/**
* @copyright   (C) 2010 iJoomla, Inc. - All rights reserved.
* @license  GNU General Public License, version 2 (http://www.gnu.org/licenses/gpl-2.0.html) 
* @author  iJoomla.com webmaster@ijoomla.com
* @url   http://www.ijoomla.com/licensing/
* the PHP code portions are distributed under the GPL license. If not otherwise stated, all images, manuals, cascading style sheets, and included JavaScript  
* are NOT GPL, and are released under the IJOOMLA Proprietary Use License v1.0 
* More info at http://www.ijoomla.com/licensing/
*/

defined('_JEXEC') or die('Restricted access');
	
class QuestionConstant{
	
	function QuestionConstant(){
	}
	
	function display($orientation = "", $question_id, $survey_id, $params, $question_details, $completed, $session_id){								
		$return_content_array = array();
		$return = "";
		$answer = "";
		$question_class = isset($params->question)? $params->question : "";
		$question_description = isset($params->question_description)? $params->question_description : "";		
		$javascript = "";
		$value = "";
		$entered = "";
		$answers = $this->getAnswers($question_id);
		$validation = "";
		
		$return .= '<table class="table_question">';
		$return .= 	  '<tr>';
		$return .= 	  	 '<td class="'.$question_class.'">';
		$return .=           $question_details["0"]["title"];
		if($question_details["0"]["required"] == "1"){
			$return .= '<span class="question_required"> *</span>';
			$javascript = ' onchange="setentertext(form.q'.$question_id.', this)" ';
			$validation = $this->createValidation($question_id, $question_details["0"]["title"], $answers, $question_details);					
		}
		$return .= 	  	 '</td>';
		$return .= 	  '</tr>';
		if($question_details["0"]["description"] != ""){
			$return .='<tr>';
			$return .= 	 '<td class="'.$question_description.'">';
			$return .=       $question_details["0"]["description"];
			$return .= 	 '</td>';
			$return .='</tr>';
		}
		if(count($answers)>0){
			$edit_values = $this->getValue($question_id, $session_id);
			if($edit_values == NULL || count($edit_values) == 0){
				$entered = "";
			}
			else{
				$entered = $edit_values["0"];
			}
			$all_values = array();
			if(isset($edit_values)){
				foreach($edit_values as $key=>$edit_val){
					$all_values[$edit_val["q_id"]."_".$edit_val["a_id"]] = $edit_val["value"];
				}
			}
			foreach($answers as $key=>$value){
				$val = "";
				if(isset($all_values[$question_id."_".$value["id"]])){
					if(isset($completed["view_response"]) && $completed["view_response"]=="true"){
						$val = $all_values[$question_id."_".$value["id"]];
					}
				}
				$return .= 	  '<tr>';
				$return .= 	  	 '<td>';
				$return .= 	  	    '<input type="text" onchange="setsum(this, document.survey_content.a'.$value["id"].')" value="'.$val.'" size="4" name="question['.$question_id.'][answer]['.$value["id"].']">&nbsp;
									 <span class="'.$params->answer.'">'.$value["value"].'</span>
									 <input type="hidden" value="" id="a'.$value["id"].'" name="a'.$value["id"].'">';
				$return .= 	  	 '</td>';
				$return .= 	  '</tr>';
			}
		}
		$return .= '</table>';
		
		$return .= '<input type="hidden" value="'.$question_details["0"]["constant"].'" name="qconstant'.$question_id.'">';
		$return .= '<input type="hidden" value="" name="qconstantcache'.$question_id.'">';
		$return .= '<input type="hidden" id="q'.$question_id.'" name="q'.$question_id.'" value="'.$entered.'">';
		$return .= '<input type="hidden" id="qtext'.$question_id.'" name="qtext'.$question_id.'" value="'.$value.'">';
		$return .= '<input type="hidden" name="classes['.$question_id.']" value="QuestionConstant">';	
		
		$return_content_array["content"] = $return;
		$return_content_array["validation"] = $validation;
		
		return $return_content_array;
	}
	
	function getAnswers($question_id){
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();		
		$query->select('id, value');
		$query->from('#__ijoomla_surveys_answers');
		$query->where("question_id=".intval($question_id));	
		$query->order("id asc");	
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadAssocList();	
		return $result;
	}
	
	function createValidation($question_id, $title, $answers, $question_details){
		$result = "";
		$float_array = array();
		$or_array = array();
		
		foreach($answers as $key=>$value){
			$float_array[] = "parseFloat(document.survey_content.a".$value["id"].".value)"; 
			$or_array[] = "document.survey_content.a".$value["id"].".value<".$question_details["0"]["minvalue"]." || document.survey_content.a".$value["id"].".value>".$question_details["0"]["maxvalue"];
		}
				
		$result .= "	var checksum=0;"."\n";
		$result .= "	checksum=0 + ".implode(" + ", $float_array).";"."\n";
		$result .= "	if(".implode(" || ", $or_array)."){"."\n".
				   "		alert(AlertText +' The numbers you enter must be in the interval (".$question_details["0"]["minvalue"].", ".$question_details["0"]["maxvalue"].")');"."\n".						   
				   "		return false;"."\n".
			       "	}"."\n";
		$result .= "	if(".$question_details["0"]["constant"]."!=-1){
							if (checksum != ".$question_details["0"]["constant"]."){"."\n".
				   "			var err_msg;"."\n".
				   "			if (isNaN(checksum)==true){"."\n".
				   "				err_msg='You are not allowed to enter non numbers or leave empty choices ';"."\n".
				   "			}"."\n".
				   "			else{"."\n".
				   "				err_msg='They currently add up to total of ' + checksum;"."\n".
				   "			}"."\n".
				   "			alert(AlertText +' The choices must add up to a total of ".$question_details["0"]["constant"]." .' + err_msg  );"."\n".
				   "			return false;"."\n".
				   "		}
				   		}";					  
		return $result;
	}
	
	function save($id, $type, $session_id){
		$db =& JFactory::getDBO();
		
		$all_answers = JRequest::getVar("question");
		$answers = $all_answers[$id]["answer"];
		
		if($this->answerExist($id, $session_id)){
			$sql = "delete from  #__ijoomla_surveys_result where q_id=".$id." and session_id=".$session_id;												
			$db->setQuery($sql);
			$db->query();
		}
		
		foreach($answers as $key=>$value){
			if(trim($value) != ""){
				$sql = "insert into #__ijoomla_surveys_result(`q_id`, `a_id`, `m_id`, `ac_id`, `session_id`, `value`) values (";					
				$sql .= $id.", ".$key.", 0, 0, ".$session_id.", '".addslashes($value)."'";
				$sql .= ")";
				$db->setQuery($sql);
				$db->query();
			}
		}
	}
	
	function answerExist($question_id, $session_id){
		$db =& JFactory::getDBO();
		$sql = "select count(*) from #__ijoomla_surveys_result where q_id=".$question_id." and session_id=".$session_id;
		$db->setQuery($sql);
		$db->query();
		$result = $db->loadResult();
		if($result != "0"){
			return true;
		}
		return false;
	}
	
	function getValue($question_id, $session_id){
        if (!$session_id) { return NULL; }    
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();		
		$query->select('*');
		$query->from('#__ijoomla_surveys_result');
		$query->where("q_id=".intval($question_id)." and session_id=".intval($session_id));		
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadAssocList();	
		return $result;
	}
	
	function editResult($id, $survey_id, $params, $i, $title, $all_responses_count){
		$answers = $this->getAnswers($id);
		$answers_array = array();
		$controller = JRequest::getVar("controller", "", "get");
				
		foreach($answers as $key=>$value){			
			$answers_array[] = $value["id"];
		}		
		
		$return  = '<table width="100%" style="border:1px solid #CCCCCC; border-collapse:collapse;">';
		$return .= 		'<tr>';
		$return .= 			'<td class="'.$params->question.'" colspan="4" style="padding-left:5px;">';
		$return .= 				'<b>'.$i.". ".$title.'</b>';
		$return .= 			'</td>';
		$return .= 		'</tr>';
		$return .= 		'<tr>';
		$return .= 			'<td></td>';
		$return .= 			'<td></td>';
		$return .= 			'<td align="center">';
		$return .= 				JText::_("COM_SURVEYS_RESPONSE_PERCENT");
		$return .= 			'</td>';
		$return .= 			'<td align="center">';
		$return .= 				JText::_("COM_SURVEYS_TOTAL_RESPONSE");	
		$return .= 			'</td>';				
		$return .= 		'</tr>';
		$k = 0;
		$total_count_values = $this->countTotalValues($id, implode(",", $answers_array));		
		foreach($answers as $a_key=>$a_value){
			$class = $params->table_row1;
			if($k%2 != 0){
				$class = $params->table_row2;
			}
			$k++;
			$count 	 = $this->countTotal($a_value["id"]);						
			$count_per_value = $this->countPerValue($a_value["id"]);			
			$return .= '<tr class="'.$class.'">';
			$return .= 		'<td align="right" style="padding-right:5px;">';
			$app =& JFactory::getApplication();      	
			if($app->isAdmin()){
				if($controller != "" && $controller == "statistics"){
					$r_id = JRequest::getVar("r_id", "0");
					$link = JURI::root().'administrator/index.php?option=com_surveys&controller=editdetails&task=edit_details&q_id='.$id.'&a_id='.$a_value["id"]."&r_id=".$r_id;
					$return .= '<a style="text-decoration:none;" href="'.$link.'">'.JText::_("COM_SURVEYS_VIEW_DETAIL").'</a>'."&nbsp;&nbsp;";
				}				
			}
			else{
				$link = JRoute::_('index.php?option=com_surveys&controller=editsurvey&Itemid='.JRequest::getVar("Itemid").'&task=edit_details&q_id='.$id.'&a_id='.$a_value["id"]);
				$return .= '<a style="text-decoration:none;" href="'.$link.'">'.JText::_("COM_SURVEYS_VIEW_DETAIL").'</a>'."&nbsp;&nbsp;";
			}		
			$return .= 			$a_value["value"];
			$return .= 		'</td>';			
			$return .= 		'<td align="left" width="30%">';
			if(intval($total_count_values) != "0"){
				$return .= 		$this->getPicture(number_format( (($count_per_value * 100) / $total_count_values), 2, '.', '') );
			}
			$return .= 		'</td>';
			$return .= 		'<td align="center">';
			if(intval($total_count_values) != "0"){
				$return .= 		number_format( (($count_per_value * 100) / $total_count_values), 2, '.', ''). " %";
			}
			$return .= 		'</td>';
			$return .= 		'<td align="center">';
			$return .= 			$count_per_value;
			$return .= 		'</td>';				
			$return .= '</tr>';	
		}
		$return .= 		'<tr>';
		$return .= 			'<td colspan="3" style="padding-right:5px;" align="right">';
		$return .= 				'<b>'.JTExt::_("COM_SURVEYS_TOTAL_RESPONDENTS").':</b>';
		$return .= 			'</td>';
		$return .= 			'<td class="'.$params->total_background.'" align="center">';
		$return .= 				'<b>'.$this->countPerQuestion($id).'</b>';
		$return .= 			'</td>';
		$return .= 		'</tr>';
		$return .= '</table>';
		return $return;		
	}	
	
	function countTotalValues($id, $a_id){
		$r_id = JRequest::getVar("r_id", "");
		$and = "";
		if($r_id != ""){
			$and = " and session_id=".$r_id;
		}		
		$db =& JFactory::getDBO();		
		$sql = "select sum(value) from #__ijoomla_surveys_result where q_id=".$id." and a_id in(".$a_id.")".$and;		
		$db->setQuery($sql);
		$db->query();
		$result = $db->loadResult();
		return $result;
	}
	
	function countTotal($a_id){
		$r_id = JRequest::getVar("r_id", "");
		$and = "";
		if($r_id != ""){
			$and = " and session_id=".$r_id;
		}
		$db =& JFactory::getDBO();		
		$sql = "select count(*) from #__ijoomla_surveys_result where a_id=".$a_id.$and;		
		$db->setQuery($sql);
		$db->query();
		$result = $db->loadResult();
		return $result;
	}
	
	function countPerValue($a_id){
		$r_id = JRequest::getVar("r_id", "");
		$and = "";
		if($r_id != ""){
			$and = " and session_id=".$r_id;
		}
		$db =& JFactory::getDBO();		
		$sql = "select sum(value) from #__ijoomla_surveys_result where a_id=".$a_id.$and;		
		$db->setQuery($sql);
		$db->query();
		$result = $db->loadResult();
		return $result;
	}
	
	function countPerQuestion($id){
		$db =& JFactory::getDBO();		
		$sql = "select count(*) from #__ijoomla_surveys_result where q_id=".$id." group by session_id";		
		$db->setQuery($sql);
		$db->query();
		$result = $db->loadAssocList();
		return count($result);
	}
	
	function getPicture($value){	
	    $picture = "";
		$picture .= "<div style=\"width:100%;\">";
		$picture .= 	"<div style=\"width:" . $value . "%; background-color:#0000CC;\"> &nbsp; ";
		$picture .= 	"</div>";
		$picture .= "</div>";
		return $picture;
	}
	
	function getForHeader($id, $title){		
		return $title;
	}
	
	function getForRow($q_id, $sess_id){
		$answers = $this->getAnswers($q_id);
		$result_array = array();
		
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();		
		$query->select('sr.value as result_value, a.value as answer_value');
		$query->from('#__ijoomla_surveys_result sr, #__ijoomla_surveys_answers a');
		$query->where("sr.q_id=".intval($q_id)." and sr.session_id=".intval($sess_id)." and sr.a_id=a.id");		
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadAssocList();
		if($result == NULL || count($result) == 0){
			return "NO ANSWER";
		}
		else{
			foreach($result as $key=>$value){
				$result_array[] = trim($value["answer_value"])." = ".trim($value["result_value"]);
			} 
		}
		return implode(" AND ", $result_array);
	}
	
	function getQuestionResultForEmail($q_id, $session_id, $title){		
		$return = $title.":"."\n";
		
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();		
		$query->select('sr.value as result_value, a.value as answer_value');
		$query->from('#__ijoomla_surveys_result sr, #__ijoomla_surveys_answers a');
		$query->where("sr.q_id=".intval($q_id)." and sr.session_id=".intval($session_id)." and sr.a_id=a.id");		
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadAssocList();
		
		foreach($result as $key=>$value){
			$return .= "\t".trim($value["answer_value"]).": ".trim($value["result_value"]);
			$return .= "\n";
		}		
		return $return;
	}
	
	function checkCompleted($logic, $compare, $answer, $skip_answer){
		$return = false;		
		if($logic == "OR"){
			if($compare == "equal"){
				foreach($skip_answer as $key=>$value){
					if(isset($answer[$value]) &&  $answer[$value] != ""){
						$return = true;
						return $return;
					}
				}
			}
			elseif($compare == "different"){
				foreach($skip_answer as $key=>$value){
					if(isset($answer[$value]) &&  $answer[$value] != ""){
						$return = false;
						return $return;
					}
				}
				$return = true;
				return $return;
			}
		}
		elseif($logic == "AND"){
			if($compare == "equal"){
				foreach($skip_answer as $key=>$value){
					if(!isset($answer[$value])){
						$return = false;
						return $return;						
					}
				}
				$return = true;
				return $return;
			}
			elseif($compare == "different"){
				foreach($answer as $key=>$value){
					if(in_array($key, $skip_answer) && $value != ""){
						$return = false;
						return $return;						
					}
				}
				$return = true;
				return $return;
			}
		}			
	}
			
};

?>